import React from 'react';
import './login.css';
import { Form, Input, Button, message } from 'antd';
import { getMenu } from '../../api'
import { useNavigate, Navigate } from 'react-router-dom'

const Login = () => {
    const navigate = useNavigate()
    // 在登录状态下，需要跳转到home页面，重定向
    if (localStorage.getItem('token')) {
      return <Navigate to="/home" replace />
    }
    const handleSubmit = (val) => {
        // 在提交的时候判断用户名或密码是否填写
      if (!val.password || !val.username) {
        // 调用的message组件
        return message.open({
          type: 'warning',
          content: '请输入用户名和密码',
        });
      }
      getMenu(val).then(({ data }) => {
        // 设置缓存信息
        localStorage.setItem('token', data.data.token)
        // 跳转页面
        navigate('/home')
      })    
    }
    return (
        <Form
        className="login-container"
        onFinish={handleSubmit}
      >
        <div className="login_title">系统登录</div>
        <Form.Item
          label="账号"
          name="username"
        >
          <Input placeholder="请输入账号" />
        </Form.Item>
        <Form.Item
          label="密码"
          name="password"
        >
          <Input.Password placeholder="请输入账号" />
        </Form.Item>
        <Form.Item className="login-button">
          <Button type="primary" htmlType="submit">登录</Button>
        </Form.Item>
      </Form>
    )
}

export default Login